package com.carrental.rental.mq;

import com.carrental.rental.config.RabbitMQConfig;
import com.carrental.rental.dto.OrderCreateDTO;
import com.carrental.rental.dto.OrderDTO;
import com.carrental.rental.service.OrderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 订单消息监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderMessageListener {

    private final OrderService orderService;
    private final ObjectMapper objectMapper;

    /**
     * 处理订单创建消息
     */
    @RabbitListener(queues = RabbitMQConfig.ORDER_CREATE_QUEUE)
    public void handleOrderCreateMessage(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 解析消息内容
            String messageBody = new String(message.getBody());
            log.info("收到订单创建消息: {}", messageBody);
            String cleanedJson = messageBody.replaceAll("^\"|\"$", "").replace("\\\"", "\"");
            // 将消息转换为DTO对象
            OrderCreateDTO createDTO = objectMapper.readValue(cleanedJson, OrderCreateDTO.class);

            // 构建订单DTO
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setOrderNo(createDTO.getOrderNo());
            orderDTO.setUserId(createDTO.getCustomerId());
            orderDTO.setVehicleId(createDTO.getVehicleId());
            orderDTO.setPickupStoreId(createDTO.getPickupStoreId());
            orderDTO.setReturnStoreId(createDTO.getReturnStoreId());

            // 解析日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            orderDTO.setStartTime(LocalDateTime.parse(createDTO.getStartDate() + " 00:00:00",
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            orderDTO.setEndTime(LocalDateTime.parse(createDTO.getEndDate() + " 23:59:59",
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            orderDTO.setDays(createDTO.getDuration());
            orderDTO.setRentAmount(createDTO.getAmount().subtract(new BigDecimal(50))); // 减去服务费
            orderDTO.setDepositAmount(createDTO.getDeposit());
            orderDTO.setDiscountAmount(BigDecimal.ZERO);
            orderDTO.setPayAmount(createDTO.getAmount());
            orderDTO.setStatus(1); // 默认状态：待支付

            // 调用服务创建订单
            Long orderId = orderService.createOrder(orderDTO);
            log.info("订单创建成功，ID: {}, 订单号: {}", orderId, createDTO.getOrderNo());

            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("处理订单创建消息失败", e);
            // 拒绝消息并重新入队
            channel.basicNack(deliveryTag, false, true);
        }
    }
}